import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { req } from "@/common/methods";
import { Table, Modal, Button, Space, Radio, message, DatePicker } from "antd";
import { PlusOutlined, HistoryOutlined } from "@ant-design/icons";

import styles from "./index.module.scss";

import type { ColumnsType, TableProps } from "antd/es/table";

import EditComponent from "./edit";
import DeleteComponent from "./delete";

import locale from "antd/es/date-picker/locale/zh_CN";
import "dayjs/locale/zh-cn";
import dayjs from "dayjs";

type DataType = any;

const onChange: TableProps<DataType>["onChange"] = (
  pagination,
  filters,
  sorter,
  extra
) => {
  console.log("params", pagination, filters, sorter, extra);
};

let easyVal = {};
let allDepart = {};
let allSupplies = {}; //以后做
const DailyTable: React.FC = (props) => {
  const navigate = useNavigate();
  const isIn = props.method === "in";
  //console.log(isIn);
  const methodArr = {
    0: "全部",
    10: isIn ? "进货" : "退货",
    20: isIn ? "退库" : "领用",
    30: isIn ? "盘盈" : "盘亏",
  };
  const [showMethod, setShowMethod] = useState(0);
  const columns: ColumnsType<DataType> = [
    {
      title: (isIn ? "入库" : "出库") + "方式",
      dataIndex: "method",
      render(record) {
        return (
          <>
            <div
              style={{ color: { 10: "blue", 20: "green", 30: "red" }[record] }}
            >
              {methodArr[record] || record}
            </div>
          </>
        );
      },
    },
    {
      title: "物品名称",
      dataIndex: "goods_id",
      render(id) {
        return (
          <>
            {easyVal[id] && easyVal[id].name ? (
              "" + easyVal[id].name
            ) : (
              <>
                <font color="red">已删除物品[{id}]</font>
              </>
            )}
          </>
        );
      },
    },
    {
      title: "单位",
      dataIndex: "goods_id",
      render(id) {
        return (
          <>{easyVal[id] && easyVal[id].unit ? "" + easyVal[id].unit : `-`}</>
        );
      },
    },
    {
      title: "数量",
      dataIndex: "change_count",
      render: (num) => Math.abs(num),
    },
    {
      title: "结余",
      dataIndex: "after_count",
    },
    {
      title: isIn ? "供货商" : "部门",
      dataIndex: "depart",
      render(record, currentItem) {
        return currentItem.method === 30 ? (
          <>-</>
        ) : (
          <div
            style={{
              color: (
                currentItem.method === 20
                  ? allDepart[record]
                  : allSupplies[record]
              )
                ? "black"
                : "red",
            }}
          >
            {(currentItem.method === 20
              ? allDepart[record]
              : allSupplies[record]) ||
              `未知${isIn ? "供应商" : "部门"}[${record}]`}
          </div>
        );
      },
      sorter: (a, b) => {
        const v1 = ("" + a.depart).charAt(0);
        const v2 = ("" + b.depart).charAt(0);
        return v1.localeCompare(v2, "zh-CN");
      },
      // filters: (()=>{
      //     let res = [];
      //     try{
      //       res = data.map(item => item.depart).filter((item1,index1,arr1) => arr1.indexOf(item1) == index1).map(item2 => ({text:item2,value:item2}));
      //     }catch(e){
      //       message.error(''+e);
      //     }
      //     //console.log(res);
      //     return res;
      // })(),
      // filterMode: 'tree',
      // filterSearch: true,
      // onFilter: (value: string, record) => (''+record.depart).startsWith(value),
    },
    {
      title: isIn ? "进货人" : "申请人",
      dataIndex: "requ",
    },
    {
      title: isIn ? "确认人" : "领用人",
      dataIndex: "empl",
    },
    {
      title: "时间",
      dataIndex: "time",
    },
    {
      title: "备注",
      dataIndex: "remark",
    },
    {
      title: "操作",
      dataIndex: "id",
      width: 55,
      render(id, record) {
        return (
          <>
            <div className={styles["btn-area"]}>
              <Button
                size="small"
                type="primary"
                onClick={() => {
                  Modal.info({
                    title: "修改单据",
                    content: (
                      <EditComponent
                        record={record}
                        doClose={() => {
                          preFetch();
                        }}
                      />
                    ),
                    closable: true,
                    footer: <></>,
                    width: 650,
                  });
                }}
              >
                修改
              </Button>
              <Button
                size="small"
                type="primary"
                danger
                onClick={() => {
                  Modal.warning({
                    title: "撤销单据",
                    content: (
                      <DeleteComponent
                        record={record}
                        doClose={() => {
                          preFetch();
                        }}
                      />
                    ),
                    closable: true,
                    footer: <></>,
                    width: 520,
                  });
                }}
              >
                撤销
              </Button>
            </div>
          </>
        );
      },
    },
  ];
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [tableParams, setTableParams] = useState<TableParams>({
    pagination: {
      current: 1,
      pageSize: 10,
    },
  });

  const fetchData = (query: { month: string; method: number }) => {
    setLoading(true);
    return req("/api/goods/easy_get")
      .then((data0) => {
        easyVal = { ...data0 };
        //return req(`/api/${isIn?'suppliers':'depart'}/get`);//获取部门或供货商数据
        return req(`/api/depart/get`); //获取部门或供货商数据
      })
      .then((data) => {
        allDepart = {};
        //console.log('data',data);
        data.forEach((item) => {
          allDepart[item.id] = item.name;
        });
        return req(`/api/suppliers/get`); //获取供货商数据
      })
      .then((data) => {
        allSupplies = {};
        data.forEach((item) => {
          allSupplies[item.id] = item.name;
        });
        //console.log(allDepart);
        return req(`/api/storage/${isIn ? "in" : "out"}/get_all`, query, "get"); //获取表内数据
      })
      .then((data) => {
        setData(data);
        setLoading(false);
      })
      .catch((msg) => {
        Modal.error({
          title: "系统出错",
          content: (
            <div>
              <pre>{"" + msg}</pre>
            </div>
          ),
        });
      });
  };
  const [showMonth, setShowMonth] = useState(
    (() => {
      const date = new Date();
      return `${date.getFullYear()}-${("" + (date.getMonth() + 1)).padStart(
        2,
        "0"
      )}`;
    })()
  );
  const preFetch = () => {
    fetchData({
      method: showMethod,
      month: showMonth,
    });
  };
  useEffect(() => {
    preFetch();
  }, [JSON.stringify(tableParams), showMethod, showMonth]);

  return (
    <>
      <div className={styles.toolbar}>
        <Space>
          {loading || (
            <Radio.Group value={`${showMethod}`} buttonStyle="solid">
              {Object.keys(methodArr).map((key) => {
                //console.log(key)
                return (
                  <Radio.Button
                    value={key}
                    checked={showMethod == key}
                    key={key}
                    onClick={(e) => setShowMethod(e.target.value)}
                  >
                    {methodArr[key]}
                  </Radio.Button>
                );
              })}
              {/* <Radio.Button value={0} onClick={()=>setShowMethod(0)}>全部</Radio.Button>
                    <Radio.Button value={10}>{isIn?'进货':'退货'}</Radio.Button>
                    <Radio.Button value={20}>{isIn?'收回':'领用'}</Radio.Button>
                    <Radio.Button value={30}>{isIn?'盘盈':'盘亏'}</Radio.Button> */}
            </Radio.Group>
          )}
          <DatePicker
            defaultValue={dayjs(showMonth)}
            locale={locale}
            onChange={(date, dateString) => {
              setShowMonth(dateString);
            }}
            picker="month"
          />{" "}
          <Button
            icon={<HistoryOutlined />}
            onClick={() => {
              //Modal.error({title:'未启用',content:<>功能还在开发中</>})
              navigate("/management/lib/history");
            }}
          >
            历史单据
          </Button>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={() =>
              navigate(`/management/lib/${isIn ? "in" : "out"}_storage/add`)
            }
          >
            添加{isIn ? "入" : "出"}库单
          </Button>
        </Space>
      </div>
      <Table
        columns={columns}
        rowKey={(record) => record.id}
        dataSource={data}
        loading={loading}
      />
    </>
  );
  // onChange={onChange}
};

export default DailyTable;
